#include "../core/Core.h"
#include "../core/Logger.h"
#include "../core/ObjectFactory.h"
#include "../console/NetConsole.h"
#include "../horde3d/h3d.h"
#include "../revel/RevelEncoder.h"
#include "../sdl/SDLGo.h"
#include "../k2graphics/plk2gfx.h"

int main(int argc, char** argv)
{
	std::string logname = "log.txt";

	if(argc > 1)
	{
		std::string temps(argv[1]);
		if(temps == "-log")
		{
			logname = std::string(argv[2]);
		}
	}

	Logger::init(logDEBUG2, logname.c_str());
	LOG(logINFO) << "Logging started.";

	//LOG(logINFO) << "Do I exist?: " << g_register_horde3d_object.bla->getCppTypeName();
	LOG(logINFO) << "Eh? " << returnThreePlusX(15) << ", " << returnFourPlusX(15);

	LOG(logINFO) << "Registered cpp prototypes: ";
	SingletonCppProtoDepot::get()->debugListProtos();

	LOG(logDEBUG) << "Creating sheet.";
	Core core(argc, argv);
	std::string objname = "game.testmaster";
	std::vector<std::string> masterNames = core.getSysArg("-master");
	if(masterNames.size() > 0)
		objname = masterNames[0];
	core.addGlobalObject(new SDLGo(&core), "SDLGo");
	core.createSheet(objname);
	//um.createSheet(); // don't create any objects at the moment...
	LOG(logDEBUG) << "Sheet created.";

	int conPort = 0;
	NetConsole* nc = NULL;
	std::vector<std::string> portOpts = core.getSysArg("-consoleport");
	if(portOpts.size() > 0)
	{
		conPort = atoi(portOpts[0].c_str());
		if(conPort > 0)
		{
			LOG(logDEBUG) << "Creating net console.";
			LOG(logDEBUG) << "Using console port " << conPort;
			
			nc = new NetConsole(&core, conPort);
	
			std::vector<std::string> whitelist = core.getSysArg("-whitelist");
			for(int i = 0; i < whitelist.size(); ++i)
			{
				nc->whitelistAddress(whitelist[i]);
				LOG(logDEBUG) << "Whitelisting " << whitelist[i];
			}

			LOG(logDEBUG) << "Net console created.";
		}
	}
	//NetConsole nc(&core, conPort);
	//nc.whitelistAddress("127.0.0.1");

	// Timing variables
	Uint32 old_time, current_time;
	float ftime;

	// Need to initialize this here for event loop to work
	current_time = SDL_GetTicks();

	while(!core.quitSignal())
	{
		old_time = current_time;
		current_time = SDL_GetTicks();
		ftime = (current_time - old_time) / 1000.0f;
		core.updateGlobalObjects(ftime);
		core.updateAllSheets(ftime);
	}

	LOG(logDEBUG) << "Quitting....";

	delete nc;

	LOG(logDEBUG) << "Deconstruction beginning...";

	return 0;
}
